package com.zhu.transaction.controller;


import com.zhu.transaction.pojo.Message;
import com.zhu.transaction.pojo.User;
import com.zhu.transaction.pojo.state.BackState;
import com.zhu.transaction.pojo.state.R;
import com.zhu.transaction.service.MessageService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhu
 * @since 2021-01-07
 */
@Controller
@RequestMapping("/message")
public class MessageController {

    @Autowired
    MessageService messageService;

    @ResponseBody
    @PostMapping("/add")
    @ApiOperation(tags = "添加一条留言", value = "")
    public R addMessage(@RequestBody Message message, HttpSession session) {
        User user = (User) session.getAttribute("user");
        message.setSendUser(user.getId());
        message.setSendUserPojo(user).setReceiveUser("0");
        BackState result = messageService.addMessage(message);
        return result == BackState.SUCCESS ? R.ok().message("留言成功") : R.error().message("留言失败");
    }

    @ResponseBody
    @PostMapping("/update")
    @ApiOperation(tags = "更新留言状态", value = "")
    public R updateMessage(String messageId) {
        return messageService.updateMessage(messageId) == BackState.SUCCESS ? R.ok() : R.error();
    }

    @ResponseBody
    @PostMapping("/delete")
    @ApiOperation(tags = "删除一条留言", value = "")
    public R deleteMessage(String messageId) {
        BackState result = messageService.deleteOneMessage(messageId);
        return result == BackState.SUCCESS ? R.ok() : R.error();
    }

    @ResponseBody
    @GetMapping("/unReadCount")
    @ApiOperation(tags = "查询未读留言数量", value = "")
    public R getUnReadCount(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer count = messageService.getUnReadMessageCount(user.getId());
        return R.ok().data("count", count);
    }

    @RequestMapping("/list")
    @ApiOperation(value = "查询留言列表", hidden = true)
    public String getMessageList(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Message> messageList = messageService.getMessageByReceiveUser(user.getId());
        model.addAttribute("messageList", messageList);
        return "main/message";
    }
}

